package com.example.netty.realNetty.packet;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class Server {
    public static void main(String[] args) {
        NioEventLoopGroup boos = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boos,work);
            bootstrap.channel(NioServerSocketChannel.class);
            //设置 NioServerSocketChannel 的属性
            //调整系统的接收缓冲区(滑动窗口)
            //todo 不明白调整系统的滑动窗口造成的影响结果
            //bootstrap.option(ChannelOption.SO_RCVBUF,1);

            //调成 netty 的接收缓冲区(ByteBuf)
            bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                    new AdaptiveRecvByteBufAllocator(32,32,32));
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    //定长读取
                    //sc.pipeline().addLast(new FixedLengthFrameDecoder(10));
                    //按照分割符读取 "\n","\r\n"
                    //todo 虽然接收缓冲区,设置了32,但结果却输出超过了32
                    sc.pipeline().addLast(new LineBasedFrameDecoder(1024));
                    sc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                }
            });
            ChannelFuture sync = bootstrap.bind(8080).sync();
            //todo 没看懂,不明白这一步要干什么,没发现close方法
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            boos.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
